package com.orangelife.mobile.main.fragment;

import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.curry.android.http.OrangeDataHandler;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.IntentHelper;
import com.curry.android.util.JSONHelper;
import com.curry.orangelife.mobile.R;
import com.google.gson.reflect.TypeToken;
import com.markupartist.android.widget.PullToRefreshListView;
import com.orangelife.mobile.common.biz.PullListViewImpl;
import com.orangelife.mobile.common.biz.PullListViewRefreshOrLoad;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.constants.ParkingCardURL;
import com.orangelife.mobile.parkingcard.activity.ApplyForParkingCardBeginActivity;
import com.orangelife.mobile.parkingcard.adapter.PayRecordAdapter;
import com.orangelife.mobile.util.JsonReponseHandler;
import com.orangelife.mobile.util.StringUtil;
import com.orangelife.mobile.util.ToastHelper;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;

/**
 * 公共停车
 * Created by yw on 2015/11/25.
 */
public class ParkingCardFragment extends Fragment {
    /**标题*/
    private TextView tvTitle;
    /**累计缴费*/
    private TextView tvTotalRecharge;
    /**上次缴费时间*/
    private TextView tvLastTimeRechargeTime;
    /**无停车卡时显示广告*/
    private RelativeLayout rlParkingCarApply;
    /**有停车卡时显示列表*/
    private RelativeLayout rlPayRecord;
    /**缴费记录*/
    private PullToRefreshListView lvPayRecord;
    /** 初始化页数 */
    private int pageNo = Constant.PAGE_NO_DEFAULT;
    /** 初始化页面的数据数量 */
    private int pageSize = Constant.PAGE_SIZE_DEFAULLT;
    /** 缴费适配器*/
    private PayRecordAdapter<Map<String,Object>> adapter;
    private static final int PAY_RECORD = 0;
    private List<Map<String,Object>> recordList,recordList2;
    private Handler mHandler;
    private PullListViewRefreshOrLoad pullListView;
    private String cardsID;
    private Button btnApplyParkingCard;
    private View view;
    private Dialog dialog;
    private RelativeLayout rlTitleBar;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if(view ==null)
            view =inflater.inflate(R.layout.activity_parking_card_fee_mine,null,false);
        initView();
        setRequestCard();
        setAdapter();
        getMyPayRecordFromServer();
        pullListView();
        return view;
    }

    /**
     * 判断是否有停车卡
     */
//    private void setRequestCard(){
//        //		String url = Constant.URL_PARKCARD_ISCARD;
//        //		JSONRequest.getInstance().sendRequest(JSONRequest.GET, url, null, handler, CARD, HttpUtil.ACTION_URI);
//        Map<String, Object> map = new HashMap<String, Object>();
//        Map<String, Object> rootMap = new HashMap<String, Object>();
//        rootMap.put("map", map);
//// //       rootMap.put("url", Constant.URL_PARKCARD_LIST);
//        rootMap.put("url", ParkingCardURL.PARKCARD_LIST);
//        rootMap.put("wat", 1);
//       new JSONRequest(JSONRequest.GET, rootMap, handler, HttpUtil.ACTION_URI);
//
//    }
    private void setRequestCard(){
        HashMap<String, String> map = new HashMap<String, String>();
        VolleyHttpUtil.getInstance().getWithCallback(ParkingCardURL.PARKCARD_LIST,map, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject jsonObject, int i) {
                @SuppressWarnings("unchecked")
                Map<String, Object> mapDetail = JSONHelper.jsonobjToMap(jsonObject);
                if(mapDetail.size()>0){
                    if(mapDetail.get("count").equals("0")){/**没停车卡*/
                        rlParkingCarApply.setVisibility(View.VISIBLE);
                    }else {/**有停车卡*/
                        rlPayRecord.setVisibility(View.VISIBLE);
                    }
                }else{/**没有停车卡*/
                    rlParkingCarApply.setVisibility(View.VISIBLE);
                }
            }
        });
    }

//    private void getMyPayRecordFromServer() {
//        dialog=DialogHelper.getInstance().createLoadingDialog(getActivity(),"正在加载，请稍候...");
//        dialog.show();
////        String url = Constant.URL_PARKCARD_PAY_MINE;
//        String url = ParkingCardURL.PARKCARD_PAY_MINE;
//        Map<String,Object> map = new HashMap<String, Object>();
//        map.put("pageIndex",pageNo);
//        map.put("pageSize", pageSize);
//        JSONRequest.getInstance().sendRequest(JSONRequest.GET, url, map, handler, PAY_RECORD, HttpUtil.ACTION_URI);
//    }
private void getMyPayRecordFromServer() {
    dialog=DialogHelper.getInstance().createLoadingDialog(getActivity(),"正在加载，请稍候...");
    dialog.show();
//        String url = Constant.URL_PARKCARD_PAY_MINE;
    String url = ParkingCardURL.PARKCARD_PAY_MINE;
    HashMap<String,String> map = new HashMap<String, String>();
    map.put("pageIndex",String.valueOf(pageNo));
    map.put("pageSize", String.valueOf(pageSize));

    VolleyHttpUtil.getInstance().getWithCallback(url,map, new VolleyHttpUtil.ResponseCallBack() {
        @Override
        public void handleResponse(JSONObject jsonObject, int i) {
            recordList2 = OrangeDataHandler.getListFromJsonWithPageEntity(
                    jsonObject, new TypeToken<List<Map<String, Object>>>() {
                    }.getType(), adapter, dialog);
            updateListView(recordList2);
            if(recordList2.size()>0){
                setText(recordList2.get(0).get("total").toString(), recordList2.get(0).get("latest_time").toString());
            }
        }
    });
}



    private void pullListView() {
        pullListView = new PullListViewImpl() {
            @Override
            public void refresh() {
                recordList.clear();
                pageNo = 1;
                notifyPage();
            }
            @Override
            public void loadMore() {
                pageNo += 1;
                notifyPage();
            }
        };
        pullListView.pullListView(lvPayRecord, mHandler);
    }

    /**
     * 更新界面
     */
    @SuppressWarnings("unchecked")
    private void setList() {
        adapter.setList(recordList);
        adapter.notifyDataSetChanged();
    }

    private void setAdapter() {
        recordList = new ArrayList<Map<String,Object>>();
        adapter = new PayRecordAdapter<Map<String,Object>>(getActivity(),recordList);
        lvPayRecord.setPullLoadEnable(false);
        lvPayRecord.setAdapter(adapter);
    }

    private void initView() {
        btnApplyParkingCard = (Button) view.findViewById(R.id.btnApplyParkingCard);
        tvTitle = (TextView) view.findViewById(R.id.tvTitle);
        tvTotalRecharge = (TextView) view.findViewById(R.id.tvTotalRecharge);
        tvLastTimeRechargeTime = (TextView) view.findViewById(R.id.tvLastTimeRechargeTime);
        rlParkingCarApply = (RelativeLayout) view.findViewById(R.id.rlParkingCarApply);
        rlPayRecord = (RelativeLayout) view.findViewById(R.id.rlPayRecord);
        lvPayRecord = (PullToRefreshListView) view.findViewById(R.id.lvPayRecord);
        tvTitle = (TextView) view.findViewById(R.id.tv_title);
        rlTitleBar = (RelativeLayout) view.findViewById(R.id.rlTitleBar);
        rlTitleBar.setVisibility(View.GONE);
        tvTitle.setText(R.string.park_pay_mine);
        mHandler = new Handler();
        btnApplyParkingCard.setOnClickListener(listener);
    }

    /**
     * 请求数据与更新界面
     */
    private void notifyPage() {
        getMyPayRecordFromServer();
        pullListView.onLoad(lvPayRecord);
        if (recordList != null) {
            adapter.setList(recordList);
            adapter.notifyDataSetChanged();
        }
    }

    Handler handler = new Handler(){
        @SuppressWarnings("unchecked")
        public void handleMessage(android.os.Message msg) {
            DialogHelper.closeDialog(dialog);
            switch (msg.what) {
                case PAY_RECORD:
                    recordList2 = JsonReponseHandler.getListFromJson(
                            String.valueOf(msg.obj), adapter, dialog);
                    updateListView(recordList2);
                    if(recordList2.size()>0){
                        setText(recordList2.get(0).get("total").toString(), recordList2.get(0).get("latest_time").toString());
                    }
                    break;
                case 1:
                    @SuppressWarnings("unchecked")
                    Map<String, Object> mapDetail = (Map<String, Object>) JSONHelper.jsonToMap(
                            msg.obj.toString());
                    if(mapDetail.size()>0){
                        if(mapDetail.get("count").equals("0")){/**没停车卡*/
                            rlParkingCarApply.setVisibility(View.VISIBLE);
                        }else {/**有停车卡*/
                            rlPayRecord.setVisibility(View.VISIBLE);
                        }
                    }else{/**没有停车卡*/
                        rlParkingCarApply.setVisibility(View.VISIBLE);
                    }
                    break;
                case 500:
                    ToastHelper.getInstance()._toast(
                            msg.obj.toString());
                    break;
                default:
                    break;
            }
        };
    };

    /**
     * 设置累计缴费总额和上次缴费时间
     */
    private void setText(String countCost,String time){
        if(StringUtil.isBlank(countCost)){
            tvTotalRecharge.setText(Constant.RMB_FLAG+"0.00");
        }else{
            tvTotalRecharge.setText(Constant.RMB_FLAG+countCost);
        }
        if(StringUtil.isBlank(time)){
            tvLastTimeRechargeTime.setText("暂无");
        }else{
            tvLastTimeRechargeTime.setText(time);
        }
    }
    /**
     * 刷新下拉列表
     *
     * @param list2
     */
    private void updateListView(List<Map<String, Object>> list2) {
        /** 判断list2是否为空 */
        if (list2 != null && recordList != null) {
            if (list2.size() == 0) {
                lvPayRecord.setPullLoadEnable(false);
                setList();
            } else {
                lvPayRecord.setPullLoadEnable(true);
                recordList.addAll(list2);
                setList();
            }
        } else {
            lvPayRecord.setPullLoadEnable(false);
        }
    }
    public View.OnClickListener listener = new View.OnClickListener() {

        @Override
        public void onClick(View view) {

            switch (view.getId()) {
                case R.id.btnApplyParkingCard:

                    IntentHelper.getInstances().getIntent(getActivity(), ApplyForParkingCardBeginActivity.class);
                    getActivity().finish();
                    break;

                default:
                    break;
            }
        }
    };


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
